package com.boruan.shengtangfeng.admin.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.ServletRequest;

import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.boruan.shengtangfeng.admin.jwt.UserSubject;
import com.boruan.shengtangfeng.admin.jwt.util.JwtUtil;
import com.boruan.shengtangfeng.core.entity.Log;
import com.boruan.shengtangfeng.core.entity.Role;
import com.boruan.shengtangfeng.core.entity.Log.OperateType;
import com.boruan.shengtangfeng.core.service.ILogService;
import com.boruan.shengtangfeng.core.service.IPermissionService;
import com.boruan.shengtangfeng.core.service.IRoleService;
import com.boruan.shengtangfeng.core.service.IUserService;
import com.boruan.shengtangfeng.core.utils.GlobalReponse;
import com.boruan.shengtangfeng.core.utils.ZTree;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/admin/role")
@Api(value = "", tags = { "NO:5 角色权限相关接口" })
public class RoleApi {

	@Autowired
	private ILogService sysLogService;
	@Autowired
	private IUserService userService;
	@Autowired
	private IRoleService roleService;
	@Autowired
	private IPermissionService permissionService;

	@GetMapping(value = "/get")
	@ApiOperation(value = "NO:5-1 获取角色详情", notes = "")
	public GlobalReponse<Role> get(String id) {
		Role role = new Role();
//		ShiroUser shiroUser=(ShiroUser)SecurityUtils.getSubject().getPrincipal();
		if (id != null) {
			role = roleService.findById(Long.valueOf(id));
		}
		return GlobalReponse.success(role);
	}

	@PostMapping(value = "/update")
	@ApiOperation(value = "NO:5-2 更新或者添加角色", notes = "")
	public GlobalReponse add(Role role) {
		UserSubject userSubject = JwtUtil.getCurrentJwtUser();
		Log sysLog = new Log();
		if (role.getId() != null) {
			// 更新
			Role role1 = roleService.findById(Long.valueOf(role.getId()));
			role1.setName(role.getName());
			role1.setDscn(role.getDscn());
			roleService.save(role1);
			sysLog.setObjectId(role1.getId());
			sysLog.setContent("后台管理新增角色信息");
			sysLog.setOperateType(OperateType.ADD);
		} else {
			// 添加
			role.setIsDeleted(false);
			role.setIsSystemRole(false);
			roleService.save(role);
			sysLog.setObjectId(role.getId());
			sysLog.setContent("后台管理添加角色信息");
			sysLog.setOperateType(OperateType.UPDATE);
		}
		try {
			sysLog.setCreateTime(new Date());
			sysLog.setOperater(userSubject.getId());
			sysLog.setLogType(Log.LogType.ADMIN);
			sysLogService.save(sysLog);
		} catch (Exception e) {
			log.error("后台管理保存权限失败：{}", e.getMessage());
			return GlobalReponse.fail();
		}
		return GlobalReponse.success();
	}

	/**
	 * 获取角色管理分页数据
	 */
	@GetMapping(value = "/page")
	@ApiOperation(value = "NO:5-3 分页查询角色", notes = "")
	public GlobalReponse<PageQuery<Role>> page(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
			Model model) {
//		ShiroUser shiroUser=(ShiroUser)SecurityUtils.getSubject().getPrincipal();
		PageQuery<Role> query = new PageQuery<Role>();
		query.setPageNumber(pageNo);
		Role role = new Role();
		roleService.pageQuery(query, role);
		return GlobalReponse.success(query);
	}

	@PostMapping(value = "/editPermission/{roleId}")
	@ApiOperation(value = "NO:5-4 更新角色的权限信息", notes = "")
	public GlobalReponse editPermission(ServletRequest request, @PathVariable Long roleId, String permission) {
		try {
			UserSubject userSubject = JwtUtil.getCurrentJwtUser();
			Role role = roleService.findById(roleId);
			role.setPermissions(permission);
			roleService.save(role);
			Log sysLog = new Log();
			sysLog.setContent("后台管理保存角色权限信息");
			sysLog.setCreateTime(new Date());
			sysLog.setOperater(userSubject.getId());
			sysLog.setLogType(Log.LogType.ADMIN);
			sysLog.setOperateType(OperateType.UPDATE);
			sysLog.setObjectId(role.getId());
			sysLogService.save(sysLog);
			return GlobalReponse.success();
		} catch (Exception e) {
			log.error("后台管理保存角色权限失败：{}", e.getMessage());
			return GlobalReponse.fail();
		}
	}

	/**
	 * 封装成ztree所需的js格式
	 * 
	 * @param request
	 * @return
	 */
	@GetMapping(value = "/allPermission")
	@ApiOperation(value = "NO:5-5 获取权限树信息", notes = "")
	public List<ZTree> allPermission(ServletRequest request) {
		return permissionService.buildZTree();
	}

	/**
	 * @param request
	 * @param roleId
	 * @return
	 */
	@GetMapping(value = "/getPermission/{roleId}")
	@ApiOperation(value = "NO:5-6 获取某个角色的权限", notes = "")
	public List<String> getPermission(ServletRequest request, @PathVariable Long roleId) {
		Role role = roleService.findById(roleId);
		return role.getPermissionList();
	}

}
